﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using DeskSMSFront.Properties;

namespace DeskSMSFront {

    public partial class MainWindow : Form {

        public MainWindow() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            string email = txtUsername.Text.ToLower();
            string Auth = GetAuthCode(GoogleLogin(email, txtPassword.Text, "ah", "desksms", "https://www.google.com/accounts/ClientLogin"));
            string SACSID = GetSACSID("https://desksms.appspot.com/_ah/login?auth=" + Auth);
            textBox1.Text = BucketCall("https://desksms.appspot.com/api/v1/user/" + email + "/sms?after_date=1333252800000", SACSID);
            TextMessageManager textMessages = Newtonsoft.Json.JsonConvert.DeserializeObject<TextMessageManager>(textBox1.Text);
        }

        public string GoogleLogin(string Email, string Password, string Service, string Source, string website) {
            string postdata = string.Format("accountType=GOOGLE&Email={0}&Passwd={1}&service={2}&source={3}", Email, Password, Service, Source);
            string data = PostData(website, postdata);
            return data;
        }

        private string GetAuthCode(string Data) {
            return Data.Split(new string[] { "Auth=" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
        }

        public string PostData(string Address, String Data) {
            var cookies = new CookieContainer();
            ServicePointManager.Expect100Continue = false;

            var request = (HttpWebRequest)WebRequest.Create(Address);
            request.CookieContainer = cookies;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            using (var requestStream = request.GetRequestStream())
            using (var writer = new StreamWriter(requestStream)) {
                writer.Write(Data);
            }

            using (var responseStream = request.GetResponse().GetResponseStream())
            using (var reader = new StreamReader(responseStream)) {
                var result = reader.ReadToEnd();
                return result;
            }
        }

        public static string GetSACSID(string URI) {
            var request = (HttpWebRequest)WebRequest.Create(URI);
            request.AllowAutoRedirect = false;
            var resp = request.GetResponse();
            string cookie = resp.Headers["Set-Cookie"];
            if (!cookie.StartsWith("SACSID="))
                throw new Exception("bork bork");
            cookie = cookie.Substring(7);
            if (cookie.Contains(";"))
                cookie = cookie.Substring(0, cookie.IndexOf(";"));
            return cookie;
        }

        public static string BucketCall(string URI, string Cookie) {
            var request = (HttpWebRequest)WebRequest.Create(URI);
            request.Headers.Add("Cookie", "SACSID=" + Cookie);
            request.Headers.Add("X-Same-Domain", "1");
            using (var responseStream = request.GetResponse().GetResponseStream())
            using (var reader = new StreamReader(responseStream)) {
                var result = reader.ReadToEnd();
                return result;
            }
        }

        private void MainWindow_FormClosed(object sender, FormClosedEventArgs e) {
            Settings.Default.Save();
        }

        private void button2_Click(object sender, EventArgs e) {
            SpeechBalloon balloon = new SpeechBalloon();
            balloon.Text = "the quick fox jumps over the lazy brown dog";

            balloon.Font = new Font("Comic Sans MS", 9, FontStyle.Regular);
            balloon.TextColor = Color.FromArgb(-16777216);

            balloon.Shape = BalloonShape.Rectangle;
            SizeF size = MeasureString(balloon.Text, balloon.Font);

            balloon.Left = 600;
            balloon.Top = 30;
            balloon.Width = FixBalloonSizes(size.Width);
            balloon.Height = FixBalloonSizes(size.Height);

            balloon.FillColor = Color.FromArgb(-4144960);

            balloon.BorderWidth = 3;
            balloon.BorderColor = Color.FromArgb(-5329234);

            balloon.BubbleSize = 0;
            balloon.BubbleWidth = 20;
            balloon.BubbleSmoothness = 0;

            balloon.TailLength = 119;
            balloon.TailBaseWidth = 15;
            balloon.TailRotation = 105;
            balloon.Draw(this.CreateGraphics());
        }

        private SizeF MeasureString(string s, Font f) {
            Graphics g = this.CreateGraphics();
            SizeF size = g.MeasureString(s, f);
            return size;
        }

        private int FixBalloonSizes(float f) {
            int i = (int)f;
            if (i < 50) return 50;
            return i;
        }
    }
}